/* 
 *  <copyright file="HealthCmp.cs" company="Wesley Jowitt">
 *  
 *  SobrietyEngine: Copyright (c) 2011 Wesley Jowitt
 *  
 *  This software is distributed under a software license.
 *   * As of the creation time of this file, the license in use is the Microsoft Permissive License (Ms-PL) 
 *    * The license can be viewed at:
 *     * License.Txt in the root folder of this project
 *      * http://sobrietyengine.codeplex.com/license
 *       * http://www.microsoft.com/opensource/licenses.mspx
 *       
 *  </copyright>
 *   */

using System;
using System.Collections.Generic;
using System.Text;

using Microsoft.Xna.Framework.Graphics;
using SobrietyEngine.Components.Graphic2D;
using SobrietyEngine.Components.Common;
using SobrietyEngine.Components.Player;
using SobrietyEngine.Common;
using SobrietyEngine.Guids;
using Microsoft.Xna.Framework;
using SobrietyEngine.Actor;
using SobrietyEngine.Events;
using SobrietyEngine.Events.Actor;

namespace SobrietyEngine.Components.Health
{
    public class HealthCmp : BaseComponent, SobrietyEngine.Components.IComponent
    {
        float health = 1.0f;

        OwningPlayerInfo owningPlayerInfo = null;
        //CGuid owningActor;
        CGuid playerGuid;

        public float Health
        {
            get { return health; }
            set { health = value; }
        }

        public HealthCmp()
            : base()
        {
        }

        override public void Set(Parameters parms)
        {
            if (parms.ContainsKey("Health"))
                health = (float)parms["Health"];
        }

        public override Boolean InitComponent()
        {
            base.InitComponent();
            owningPlayerInfo = (OwningPlayerInfo)ParentActor.Query(typeof(OwningPlayerInfo));
            if (owningPlayerInfo != null)
                playerGuid = owningPlayerInfo.PlayerGuid;
            else
                playerGuid = null;

            return true;
        }

        public void Hurt(float amount, CGuid hurtBy)
        {
            health -= amount;
            IActor hurter = (IActor)hurtBy.Resolve();
            if (hurter != null)
            {
                OwningPlayerInfo owningPlayerInfo = ((OwningPlayerInfo)hurter.Query(typeof(OwningPlayerInfo)));
                if (owningPlayerInfo != null)
                {
                    owningPlayerInfo.PlayerInfo.Score += (int)Math.Ceiling(amount);
                }
            }           
        }

        public void Restore(float amount)
        {
            health += amount;
        }

        new public void Update(GameTime elapsedTime)
        {
            if (health < 0.0f)
            {
                ParentActor.EventRouter.RaiseEvent(this, new ActorDied(ParentActor.Guid, playerGuid));
            }
        }
    }
}
